<?php

namespace App\Controller\Wap;

use App\Entity\Comments;
use App\Entity\OrderDeliver;
use App\Entity\Orders;
use App\Entity\ShopGoods;
use App\Entity\UserAddress;
use App\Entity\UserLikesProduct;
use App\Model\AreaModel;
use App\Model\CityModel;
use App\Model\CommentsModel;
use App\Model\OrderDeliverModel;
use App\Model\OrdersModel;
use App\Model\ProvinceModel;
use App\Model\ShopGoodsModel;
use App\Model\UserAddressModel;
use App\Model\UserLikesProductModel;
use App\Base\BaseConfig;
use App\Base\BaseController4User;
use BaseExt\KdApi;
use App\Model\LazyCommon\CCM;
use App\Model\LazyCommon\PlatConfigModel;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteExModel;
use App\Model\LazyCommon\WechatModel;
use App\Model\LazyCommon\WechatPayModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/wap")
 */
class OrderController extends BaseController4User
{

    private function initData()
    {
        return $this->data;
    }



    /**
     * @route("/order/confirm",name="UserAppOrderConfirm")
     */
    public function UserAppOrderConfirm(){

        $uid = $this->needToBeUser();
        if(!$id = $this->getParamRequired("id")){return $this->json_out(0,"参数缺失");}
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $orders = $OrdersModel->getById($id);
        if ($orders && $orders->getUid() == $uid && $orders->getStatus() < BaseConfig::__ORDER_FINISH__ && $orders->getStatus()>=BaseConfig::__ORDER_DELIVER__) {
            $orders->setStatus(BaseConfig::__ORDER_FINISH__);
            $this->myEm()->persist($orders);
            $this->myEm()->flush();
        }
        return $this->redirectToRoute("UserAppOrderComment",array("id"=>$id));
    }

    /**
     * @route("/order/comment",name="UserAppOrderComment")
     */
    public function UserAppOrderComment(){

        $uid = $this->needToBeUser();
        if(!$id = $this->getParamRequired("id")){return $this->json_out(0,"");}
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $CommentsModel = new CommentsModel($this->getDoctrine());
//        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        $orders = $OrdersModel->getById($id);

        $this->data["order"] = $orders;
        $this->data["goodsStr"] = $orders->getGoods();
        $prod = json_decode($orders->getGoods(),true);
        $total = 0;

        $this->data["canComment"] = 0;
        foreach ($prod as $id => &$item) {
            $item["score"] = 5;

            $num = $item["num"];
            $total += $item["price"] * $num;
            $this->data["goods"][] = $item;

            //检查是否已经评论过了
//            var_dump($item);
            $comment = $CommentsModel->getUserProductComment($uid,"",$item["id"]);
//            var_dump($comment);
            if ($comment) {
                $item["status"] = 2;
                $item["comment"] = $comment;
                $item["score"] = $comment->getWhat();
            }else{
                $item["status"] = 1;
                $item["comment"] = new Comments();
                $this->data["canComment"] ++;
            }

        }
        $this->data["goods"] = $prod;
        $this->data["total"] = $total;


        return $this->render("App/Wap/order_comment.php.twig",$this->data);
    }

    /**
     * @route("/order/comments/add",name="UserAppOrderCommentsAdd")
     */
    public function UserAppOrderCommentsAdd()
    {
        $uid = $this->needToBeUser();
        if(!$score = $this->getParamRequired("score")){return $this->json_out(0,"参数缺失");}
        if(!$what = $this->getParamRequired("what")){return $this->json_out(0,"参数缺失");}
        if(!$text = $this->getParamRequired("text")){return $this->json_out(0,"请输入评论内容");}
        $CommentsModel = new CommentsModel($this->getDoctrine());

        foreach ($what as $key => $value) {
            if (!isset($text[$key]) || !$text[$key]) {
                $text[$key] = "用户啥都没说，直接爽快的给了5星好评";
            }

            $CommentsModel->addProduct($uid,$what[$key],$text[$key],$score[$key]);
        }

        return $this->json_out(1,"保存成功","");
    }



    /**
     * @route("/order/info",name="UserAppOrderInfo")
     */
    public function UserAppOrderInfo(Request $request)
    {
        $uid = $this->needToBeUser();
        if(!$id = $this->getParamRequired("id")){return $this->json_out(0,"");}
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        $orders = $OrdersModel->getById($id);

        $prod = json_decode($orders->getGoods(),true);
        $total = 0;
        foreach ($prod as $id => $item) {
            $num = $item["num"];
            $total += $item["price"] * $num;
            $this->data["goods"][] = $item;
        }
        $this->data["total"] = $total;

        //获取默认地址
        $UserAddressModel = new UserAddressModel($this->getDoctrine());
        $address = $UserAddressModel->getDefault($uid);
        if ( !$address ) {
            //todo 没有地址你他妈是怎么创建订单的
        }
        $this->data["address"] = $address;
        //创建微信支付需要的参数
        //判断是本地还是远程
        $uri = $request->getUri();
        if (strpos($uri,"xy.com") > 0 ) {
            //本地测试环境
            $JsApiParam["appId"] = "";
            $JsApiParam["timestamp"] = "0";
            $JsApiParam["noncestr"] = "";
            $JsApiParam["signature"] = "";
            $this->data["server"] = "1";
        }else{
            $WechatModel = new WechatModel($this->getDoctrine());
            $WechatModel->getAccessToken();
            $WechatModel->getJsApiTicket();
            $JsApiParam = $WechatModel->createJsApiParam($request->getUri());

            $this->data["server"] = "0";
        }
        $this->data["p"] = $JsApiParam;


//        $orders->setAddtime($orders->getAddtime()->format(YYMMDDHHIISS));
//        $orders->setPaycbtime($orders->getPaycbtime()->format(YYMMDDHHIISS));
        $orders = $this->toArray($orders);
//        var_dump($orders);
        $orders["addTime"] =  $orders["addtime"]->format(YYMMDDHHIISS);
        $orders["paycbtime"] =  $orders["paycbtime"]->format(YYMMDDHHIISS);

        $orders["province"] = (new ProvinceModel($this->getDoctrine()))->getName($orders["province"]);
        $orders["city"] = (new CityModel($this->getDoctrine()))->getName($orders["city"]);
        $orders["area"] = (new AreaModel($this->getDoctrine()))->getName($orders["area"]);


        $this->data["order"] = $orders;


        //获取订单的配送信息
        $OrderDeliverModel = new OrderDeliverModel($this->getDoctrine());
        $OrderDeliver = $OrderDeliverModel->getBySn($orders["sn"]);

        $deliverOrder = "-";
        $deliverAddDate = "-";
        $deliverInfo = 0;
        $deliverData = [];


        if ($OrderDeliver) {

            //查看订单配送信息的最近更新时间，是否是6小时内刚更新过
            $lastTime = $OrderDeliver->getLastTime();
            if ($lastTime < time() - 6 * 3600) {
                //再调用一次
                $Model = new KdApi();
                $result = $Model->getOrderTracesByJson($OrderDeliver->getDeliverOrder(),$OrderDeliver->getDeliver());

                $Traces = [];
                $status = 0;
                if ($result) {
                    $data = json_decode($result,true);
                    if (isset($data["Success"]) && $data["Success"] == true) {
                        if (isset($data["State"]) && $data["State"] > 0) {
                            if ($data["State"] > 2) {
                                $status = 1;
                            }
                            $Traces = $data["Traces"];
                        }
                        $OrderDeliver->setState($data["State"]);
                    }
                }
                if (!$Traces) {
                }else{
                    $deliverInfo = 1;
                    $deliverData = $Traces;
                    $OrderDeliver->setData(json_encode($Traces))
                        ->setLastTime(time())

                    ;
                    if ($status == 1) {
                        $OrderDeliver ->setLastTime(strtotime("2050-01-01"));
                    }
                }
            }else{
                $this->log_out("get DB Data");
                $data = $OrderDeliver->getData();
                if (!$data) {
                    //没有配送数据
                }else{
                    $deliverInfo = 1;
                    $deliverData = json_decode($OrderDeliver->getData(),true);
                }
            }
            $deliverOrder = $OrderDeliver->getDeliverOrder();
            $deliverAddDate = $OrderDeliver->getAdddate();

            $this->myEm()->persist($OrderDeliver);
            $this->myEm()->flush();
        }

//        var_dump($deliverData);

        krsort($deliverData);
//        var_dump($deliverData);
        $this->data["deliverOrder"] = $deliverOrder;
        $this->data["deliverAddDate"] = $deliverAddDate;
        $this->data["deliverInfo"] = $deliverInfo;
        $this->data["deliverData"] = $deliverData;



        return $this->render("App/Wap/order_info.php.twig",$this->data);
    }



    /**
     * @route("/order/prepare",name="UserAppOrderPrepare")
     */
    public function UserAppOrderPrepare(Request $request)
    {
        $this->initData();
        $uid = $this->needToBeUser();
        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        if(!$prod = $this->getParamRequired("prod")){return $this->msg_out("参数缺失");}
        $total = 0;
        $hasVip = 0;
        foreach ($prod as $id => $num) {
            $shopGoods = $ShopGoodsModel->getById($id);
            //检查检查订单中是否有升级VIP使用的订单
            if (!$shopGoods->getIsproduct()) {
                //检查商品数量是否是1，不允许多了
                if ($num != 1) {
                    $this->setError("会员升级项目数量只能为1");
                }
                $hasVip = 1;
            }
            $total += $shopGoods->getPrice() * $num;
            $shopGoods = $this->toArray($shopGoods);
            $shopGoods["params"] = mb_split(",|\，|(\s)",$shopGoods["params"]);
            $shopGoods["num"] = $num;
            $data = ($shopGoods);
            $this->data["goods"][] = $data;

        }
        $this->data["total"] = $total;
        $this->data["hasVip"] = $hasVip;

        //获取默认地址
        $UserAddressModel = new UserAddressModel($this->getDoctrine());
        $address = $UserAddressModel->getDefault($uid);
        if ( !$address ) {
            $address = new UserAddress();
            $this->toArray($address);
            $this->setError("请先设置收货地址");
        }
        $this->data["address"] = $address;

        //创建微信支付需要的参数
        //判断是本地还是远程
        $uri = $request->getUri();
        if (strpos($uri,"xy.com") > 0 ) {
            //本地测试环境
            $JsApiParam["appId"] = "";
            $JsApiParam["timestamp"] = "0";
            $JsApiParam["noncestr"] = "";
            $JsApiParam["signature"] = "";
            $this->data["server"] = "1";
        }else{
            $WechatModel = new WechatModel($this->getDoctrine());
            $WechatModel->getAccessToken();
            $WechatModel->getJsApiTicket();
            $JsApiParam = $WechatModel->createJsApiParam($request->getUri());

            $this->data["server"] = "0";
        }


        $this->data["p"] = $JsApiParam;

        return $this->render("App/Wap/order_prepare.php.twig",$this->data);
    }




    /**
     * @route("/order/pay",name="UserAppOrderGetPayString")
     */
    public function UserAppOrderGetPayString()
    {
        $this->initData();
        $uid = $this->needToBeUser();
        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        if(!$id = $this->getParamRequired("id")){

            if(!$prod = $this->getParamRequired("prod")){return $this->msg_out("参数缺失01");}
            $total = 0;
            $totalNum = 0;
            $goodsArray = [];
            $goodsString = "";
            foreach ($prod as $id => $num) {
                $shopGoods = $ShopGoodsModel->getById($id);
                //检查检查订单中是否有升级VIP使用的订单
                if (!$shopGoods->getIsproduct()) {
                    //检查商品数量是否是1，不允许多了
                    if ($num != 1) {
                        return $this->json_out(0,"会员升级项目数量只能为1");
                    }
                }
                $total += $shopGoods->getPrice() * $num;
                $shopGoods = $this->toArray($shopGoods);
                $shopGoods["params"] = mb_split(",|\，|(\s)",$shopGoods["params"]);
                $shopGoods["num"] = $num;
                $data = ($shopGoods);
                $this->data["goods"][] = $data;
                $totalNum += $num;
                $goodsArray[] = $shopGoods;
            }
            $goodsString = json_encode($goodsArray);
            $this->data["total"] = $total;

            if ($total == 0) {
                return $this->json_out(0,"产品数不能为0");
            }
            //捐赠检查
            if(!$donate = $this->getParamRequired("donate")){$donate = 0;}
            if ($donate != 0 && $donate<0.01) {
                return $this->json_out(0,"公益捐助起点为0.01");
            }

            //检查计算的总金额和实际总金额是否相符
            if(!$sum = $this->getParamRequired("sum")){return $this->json_out(0,"参数缺失02");}

            if ($sum."" != ($total + $donate)."") {
                $total1 = $total + $donate;
                return $this->json_out(0,"数据异常，请刷新页面total=".$total1."sum=".$sum);
            }

            //获取默认地址 并对别当前的数据
            if(!$address = $this->getParamRequired("address")){return $this->json_out(0,"请先设置收货地址");}
            $UserAddressModel = new UserAddressModel($this->getDoctrine());
            $addressDefault = $UserAddressModel->getDefault($uid);
            if ( !$addressDefault ) {
                return $this->json_out(0,"请先设置收货地址");
            }
            if ($address != $addressDefault->getId()) {
                return $this->json_out(0,"收货地址数据异常请刷新页面后重新提交");
            }

            $sn = $this->createOrderSn($uid);
            $cbCode = $this->createPayCalBackCode($uid);
            $Entity = new Orders();
            $Entity->setAddtime($this->getDateTime())
                ->setUid($uid)
                ->setArea($addressDefault->getArea())
                ->setCity($addressDefault->getCity())
                ->setProvince($addressDefault->getProvince())
                ->setAddress($addressDefault->getAddress())
                ->setContact($addressDefault->getName())
                ->setPhone($addressDefault->getPhone())
                ->setDonate($donate)
                ->setNum($totalNum)
                ->setGoods($goodsString)
                ->setSid(1)
                ->setTotalGoods($total)
                ->setTotal($sum)
                ->setPaycbstatus(0)
                ->setStatus(BaseConfig::__ORDER_CREATE__)
                ->setPaytype(BaseConfig::__PAY_TYPE_WECHAT__)
                ->setPaycode($cbCode)
                ->setPaycbstatus(0)
                ->setPaycbtime($this->getDateTime(0))
                ->setSn($sn);
            $this->myEm()->persist($Entity);
            $this->myEm()->flush();
            $sum = $total + $donate;
        }else{
            $OrdersModel = new OrdersModel($this->getDoctrine());
            $order = $OrdersModel->getById($id);
            $cbCode = $order->getPaycode();
            $sum = $order->getTotal();
        }


        $WechatPayModel = new WechatPayModel($this->getDoctrine());
        $Model  = new UserModel($this->getDoctrine());
        $user = $Model->getUserById($uid);
        $opend_id = $user->getOpenid();
        $money = (int)($sum * 100);//支付金额，单位是分
//        $money = 1;//支付金额，单位是分//todo 上线删除
        $payInfo = "商城订单";
        $JsParam = $WechatPayModel->createOrder($opend_id,$payInfo,$cbCode,$money);
        if ($WechatPayModel->error) {
            return $this->json_out(0,$WechatPayModel->error);
        }
        if (!$JsParam) {
            return $this->json_out(0,"支付拉取失败");
        }

        //检查用户是否绑定上级如果否应该先提示
//        $JsParam["isBand"] = 1;
//        $UserModel = new UserModel($this->getDoctrine());
//        $user = $UserModel->getUserById($uid);
//        if ($user->getGroups() == 3) {
//            //检查是否绑定上级
//            $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
//            $userInvite = $UserInviteExModel->getUser($uid);
//            if (!$userInvite) {
//                $JsParam["isBand"] = 0;
//            }
//        }


        return $this->json_out(1,"数据获取成功",$JsParam);
    }



    /**
     * @route("/order/pay/msg",name="UserAppOrderPayCallBack")
     */
    public function UserAppOrderPayCallBack()
    {

        $postStr  = file_get_contents('php://input');
        //禁止引用外部xml实体
        $bPreviousValue = libxml_disable_entity_loader(true);
        $array_data = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        libxml_disable_entity_loader($bPreviousValue);

        if(isset($array_data['return_code']) and  $array_data['return_code'] == 'SUCCESS' ){
            //todo 检验来源的合法性
            file_put_contents("./../FileData/log_pay_cb.txt","array_data:".json_encode($array_data)."\n\n",FILE_APPEND);
            $cbCode = $array_data["out_trade_no"];//取出回调码

            $OrdersModel = new OrdersModel($this->getDoctrine());
            $OrdersModel->dealWithOrderPay($cbCode);

        }
        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';die;
    }

    /**
     * @route("/order/my",name="UserAppOrderMy")
     */
    public function UserAppOrderMy()
    {
        if(!$cur = $this->getParamRequired("cur")){$cur = "999";}
        if ($cur == "create") {
            $cur = 0;
        }
        $this->data["cur"] = $cur;

        $this->initData();
        $uid = $this->needToBeUser();
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $orders = $OrdersModel->getUserOrders($uid);
        $this->data["goods"] = $orders;
        $this->data["status"] = BaseConfig::__ORDER_STATUS_NAME__;

        return $this->render("App/Wap/orders.php.twig",$this->data);
    }




    /**
     * @route("/order/mySon",name="UserAppOrderMySon")
     */
    public function UserAppOrderMySon()
    {
        if(!$cur = $this->getParamRequired("cur")){$cur = "999";}
        if ($cur == "create") {
            $cur = 0;
        }
        $this->data["cur"] = $cur;

        $this->initData();
        $uid = $this->needToBeUser();
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $orders = $OrdersModel->getUserSonOrders($uid);
//        var_dump($orders);

        if (!$orders) {
            $orders = "";
        }
        $this->data["goods"] = $orders;
        $this->data["status"] = BaseConfig::__ORDER_STATUS_NAME__;

        return $this->render("App/Wap/orders_son.php.twig",$this->data);
    }

}
